package com.imooc.security.filter;

import com.google.common.util.concurrent.RateLimiter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName RateLimitFilter
 * @Description TODO  流控—— 继承 OncePerRequestFilter 保证过滤器里的逻辑在一个请求里只会被过滤一次
 *         TODO 在SpringBoot里，任何实现了Filter接口的类，SpringBoot会自动把它加到web应用的过滤器链里，只要声名为Component就行了
 * @Author wushaopei
 * @Date 2020/10/15 23:40
 * @Version 1.0
 */
@Order(1)
@Component
public class RateLimitFilter extends OncePerRequestFilter {

    private RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 当前请求未执行完成，则其他请求不进入，打印 too many request
        if(rateLimiter.tryAcquire()){
            filterChain.doFilter(request,response);
        }else{
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.getWriter().write("too many request!!");
            response.getWriter().flush();
            return;
        }
    }
}
